package org.hfchunya.mutualHelp.baidu;

import org.hfchunya.mutualHelp.baidu.ueditor.ActionEnter;
import org.hfchunya.mutualHelp.baidu.ueditor.define.ActionMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>百度图片上传</p>
 *
 * @author： MGARY <br/>
 * @date： 2019/2/26$ 13:22$ <br/>
 * @version： <br/>
 */
@Controller
@RequestMapping("/ueditor")
public class UeditorContorller {

    private final String PREFIX = "/ueditor/";

    /**
     * 文件地址
     */
    @Value("${web.upload-path}")
    private String fileAddress;

    /**
     * 文件处理
     */
    @Autowired
    private UeditorService ueditorService;

    /**
     * <p>测试返回地址 </p>
     *
     * @param - <br/>
     * @return <br/>
     * @throws
     * @date 2019/2/26 17:51 <br/>
     */
    @RequestMapping("")
    private String index() {
        return PREFIX + "index.html";
    }

    @ResponseBody
    @RequestMapping(value = "/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        //获取项目路径
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        //获取配置文件
        String exec = new ActionEnter(request, rootPath).exec();
        // 上传类型
        String actionType = request.getParameter("action");
        int actionCode = ActionMap.getType(actionType);
        String contextPath = request.getContextPath();
        // 文件处理
        String handlerOut = ueditorService.uploadHandle(actionCode, exec, contextPath, fileAddress);


        this.writeJson(response, handlerOut);
    }

    /**
     * <p> 数据以JSON的方式写到浏览器上 </p>
     *
     * @param resp -  <br/>
     * @param exec -  json对象 <br/>
     * @return <br/>
     * @throws
     * @date 2019/2/27 17:53 <br/>
     */
    private void writeJson(HttpServletResponse resp, String exec) {
        PrintWriter out = null;
        try {
            //设定类容为json的格式
            resp.setContentType("application/json;charset=UTF-8");
            out = resp.getWriter();
            //写到客户端
            out.write(exec);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }



}
